package ltd.newbee.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import ltd.newbee.mall.api.mall.vo.NewBeeMallOrderDetailVO;
import ltd.newbee.mall.api.mall.vo.NewBeeMallOrderItemVO;
import ltd.newbee.mall.api.mall.vo.NewBeeMallOrderListVO;
import ltd.newbee.mall.api.mall.vo.NewBeeMallShoppingCartItemVO;
import ltd.newbee.mall.common.*;
import ltd.newbee.mall.entity.*;
import ltd.newbee.mall.mapper.*;
import ltd.newbee.mall.service.NewBeeMallGoodsService;
import ltd.newbee.mall.service.NewBeeMallOrderItemService;
import ltd.newbee.mall.service.NewBeeMallOrderService;
import ltd.newbee.mall.service.NewBeeMallShoppingCartService;
import ltd.newbee.mall.util.BeanUtil;
import ltd.newbee.mall.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

@Service
public class NewBeeMallOrderServiceImpl extends ServiceImpl<NewBeeMallOrderMapper, NewBeeMallOrder> implements NewBeeMallOrderService {
    @Autowired
    private NewBeeMallOrderMapper newBeeMallOrderMapper;
    @Autowired
    private NewBeeMallOrderItemMapper newBeeMallOrderItemMapper;
    @Autowired
    private NewBeeMallOrderAddressMapper newBeeMallOrderAddressMapper;
    @Autowired
    private NewBeeMallShoppingCartService newBeeMallShoppingCartService;


    @Resource
    private NewBeeMallOrderItemService newBeeMallOrderItemService;

    @Resource
    private NewBeeMallGoodsService newBeeMallGoodsService;

    @Override
    public NewBeeMallOrderDetailVO getOrderDetailByOrderId(Long orderId) {
        NewBeeMallOrder newBeeMallOrder = findOrderByOrderId(orderId);

        if (newBeeMallOrder == null) {
            NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }

        List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemService.findByOrderId(orderId);

        //获取订单项数据
        if (!CollectionUtils.isEmpty(orderItems)) {
            List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
            NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
            BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
            newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
            newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
            newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
            return newBeeMallOrderDetailVO;
        } else {
            NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NULL_ERROR.getResult());
            return null;
        }
    }

    @Override
    public NewBeeMallOrderDetailVO getOrderDetailByOrderNo(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = findOrderByOrderNo(orderNo);
        if (newBeeMallOrder == null) {
            NewBeeMallException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        if (!userId.equals(newBeeMallOrder.getUserId())) {
            NewBeeMallException.fail(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
        }

        List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemService.findByOrderId(newBeeMallOrder.getOrderId());

        //获取订单项数据
        if (CollectionUtils.isEmpty(orderItems)) {
            NewBeeMallException.fail(ServiceResultEnum.ORDER_ITEM_NOT_EXIST_ERROR.getResult());
        }
        List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
        NewBeeMallOrderDetailVO newBeeMallOrderDetailVO = new NewBeeMallOrderDetailVO();
        BeanUtil.copyProperties(newBeeMallOrder, newBeeMallOrderDetailVO);
        newBeeMallOrderDetailVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderDetailVO.getOrderStatus()).getName());
        newBeeMallOrderDetailVO.setPayTypeString(PayTypeEnum.getPayTypeEnumByType(newBeeMallOrderDetailVO.getPayType()).getName());
        newBeeMallOrderDetailVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
        return newBeeMallOrderDetailVO;
    }

    @Override
    public PageResult getMyOrders(PageQuery pageQuery) {
        PageResult<NewBeeMallOrder> pageResult = getNewBeeMallOrdersPage(pageQuery);
        int total = pageResult.getTotalCount();
        List<NewBeeMallOrder> newBeeMallOrders = pageResult.getList();

        List<NewBeeMallOrderListVO> orderListVOS = new ArrayList<>();
        if (total > 0) {
            //数据转换 将实体类转成vo
            orderListVOS = BeanUtil.copyList(newBeeMallOrders, NewBeeMallOrderListVO.class);
            //设置订单状态中文显示值
            for (NewBeeMallOrderListVO newBeeMallOrderListVO : orderListVOS) {
                newBeeMallOrderListVO.setOrderStatusString(NewBeeMallOrderStatusEnum.getNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderListVO.getOrderStatus()).getName());
            }
            List<Long> orderIds = newBeeMallOrders.stream().map(NewBeeMallOrder::getOrderId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(orderIds)) {
                LambdaQueryWrapper<NewBeeMallOrderItem> orderQueryWrapper = Wrappers.lambdaQuery();
                orderQueryWrapper.in(NewBeeMallOrderItem::getOrderId, orderIds);
                List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemMapper.selectList(orderQueryWrapper);

                Map<Long, List<NewBeeMallOrderItem>> itemByOrderIdMap = orderItems.stream().collect(groupingBy(NewBeeMallOrderItem::getOrderId));
                for (NewBeeMallOrderListVO newBeeMallOrderListVO : orderListVOS) {
                    //封装每个订单列表对象的订单项数据
                    if (itemByOrderIdMap.containsKey(newBeeMallOrderListVO.getOrderId())) {
                        List<NewBeeMallOrderItem> orderItemListTemp = itemByOrderIdMap.get(newBeeMallOrderListVO.getOrderId());
                        //将NewBeeMallOrderItem对象列表转换成NewBeeMallOrderItemVO对象列表
                        List<NewBeeMallOrderItemVO> newBeeMallOrderItemVOS = BeanUtil.copyList(orderItemListTemp, NewBeeMallOrderItemVO.class);
                        newBeeMallOrderListVO.setNewBeeMallOrderItemVOS(newBeeMallOrderItemVOS);
                    }
                }
            }
        }
        return new PageResult<NewBeeMallOrderListVO>(orderListVOS, total, pageResult.getPageSize(), pageResult.getCurrPage());
    }

    @Override
    @Transactional
    public String cancelOrder(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = findOrderByOrderNo(orderNo);
        if (newBeeMallOrder != null) {
            //验证是否是当前userId下的订单，否则报错
            if (!userId.equals(newBeeMallOrder.getUserId())) {
                NewBeeMallException.fail(ServiceResultEnum.NO_PERMISSION_ERROR.getResult());
            }
            //订单状态判断
            if (newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus()
                    || newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()
                    || newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_EXPIRED.getOrderStatus()
                    || newBeeMallOrder.getOrderStatus().intValue() == NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }

            Date now = new Date();
            LambdaUpdateWrapper<NewBeeMallOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper
                    .set(NewBeeMallOrder::getOrderStatus, (NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_MALLUSER.getOrderStatus()) > 0 && recoverStockNum(Collections.singletonList(newBeeMallOrder.getOrderId())))
                    .set(NewBeeMallOrder::getUpdateTime, now)
                    .in(NewBeeMallOrder::getOrderId, Collections.singletonList(newBeeMallOrder.getOrderId()));

            //修改订单状态&&恢复库存
            if (newBeeMallOrderMapper.update(null, updateWrapper) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    public String finishOrder(String orderNo, Long userId) {
        NewBeeMallOrder newBeeMallOrder = findOrderByOrderNo(orderNo);
        if (newBeeMallOrder != null) {
            //验证是否是当前userId下的订单，否则报错
            if (!userId.equals(newBeeMallOrder.getUserId())) {
                return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
            }
            //订单状态判断 非出库状态下不进行修改操作
            if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_EXPRESS.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }
            newBeeMallOrder.setOrderStatus((byte) NewBeeMallOrderStatusEnum.ORDER_SUCCESS.getOrderStatus());
            newBeeMallOrder.setUpdateTime(new Date());

            LambdaUpdateWrapper<NewBeeMallOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(NewBeeMallOrder::getOrderId, newBeeMallOrder.getOrderId());
            if (newBeeMallOrderMapper.update(newBeeMallOrder, updateWrapper) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    public String paySuccess(String orderNo, int payType) {
        NewBeeMallOrder newBeeMallOrder = findOrderByOrderNo(orderNo);
        if (newBeeMallOrder != null) {
            //订单状态判断 非待支付状态下不进行修改操作
            if (newBeeMallOrder.getOrderStatus().intValue() != NewBeeMallOrderStatusEnum.ORDER_PRE_PAY.getOrderStatus()) {
                return ServiceResultEnum.ORDER_STATUS_ERROR.getResult();
            }
            newBeeMallOrder.setOrderStatus((byte) NewBeeMallOrderStatusEnum.ORDER_PAID.getOrderStatus());
            newBeeMallOrder.setPayType((byte) payType);
            newBeeMallOrder.setPayStatus((byte) PayStatusEnum.PAY_SUCCESS.getPayStatus());
            newBeeMallOrder.setPayTime(new Date());
            newBeeMallOrder.setUpdateTime(new Date());

            LambdaUpdateWrapper<NewBeeMallOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(NewBeeMallOrder::getOrderId, newBeeMallOrder.getOrderId());

            if (newBeeMallOrderMapper.update(newBeeMallOrder, updateWrapper) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            } else {
                return ServiceResultEnum.DB_ERROR.getResult();
            }
        }
        return ServiceResultEnum.ORDER_NOT_EXIST_ERROR.getResult();
    }

    @Override
    public String saveOrder(MallUser loginMallUser, MallUserAddress address, List<NewBeeMallShoppingCartItemVO> myShoppingCartItems) {
        List<Long> itemIdList = myShoppingCartItems.stream().map(NewBeeMallShoppingCartItemVO::getCartItemId).collect(Collectors.toList());
        List<Long> goodsIds = myShoppingCartItems.stream().map(NewBeeMallShoppingCartItemVO::getGoodsId).collect(Collectors.toList());

        List<NewBeeMallGoods> newBeeMallGoods = newBeeMallGoodsService.getNewBeeMallGoodsByIds(goodsIds);

        //检查是否包含已下架商品
        List<NewBeeMallGoods> goodsListNotSelling = newBeeMallGoods.stream()
                .filter(newBeeMallGoodsTemp -> newBeeMallGoodsTemp.getGoodsSellStatus() != Constants.SELL_STATUS_UP)
                .toList();
        if (!CollectionUtils.isEmpty(goodsListNotSelling)) {
            //goodsListNotSelling 对象非空则表示有下架商品
            NewBeeMallException.fail(goodsListNotSelling.get(0).getGoodsName() + "已下架，无法生成订单");
        }
        Map<Long, NewBeeMallGoods> newBeeMallGoodsMap = newBeeMallGoods.stream().collect(Collectors.toMap(NewBeeMallGoods::getGoodsId, Function.identity(), (entity1, entity2) -> entity1));
        //判断商品库存
        for (NewBeeMallShoppingCartItemVO shoppingCartItemVO : myShoppingCartItems) {
            //查出的商品中不存在购物车中的这条关联商品数据，直接返回错误提醒
            if (!newBeeMallGoodsMap.containsKey(shoppingCartItemVO.getGoodsId())) {
                NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
            }
            //存在数量大于库存的情况，直接返回错误提醒
            if (shoppingCartItemVO.getGoodsCount() > newBeeMallGoodsMap.get(shoppingCartItemVO.getGoodsId()).getStockNum()) {
                NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
            }
        }
        //删除购物项
        if (!CollectionUtils.isEmpty(itemIdList) && !CollectionUtils.isEmpty(goodsIds) && !CollectionUtils.isEmpty(newBeeMallGoods)) {
            if (newBeeMallShoppingCartService.deleteByIds(itemIdList, loginMallUser.getUserId()) > 0) {
                List<NewBeeMallGoods> updateGoods = new ArrayList<>();
                //更新商品库存
                for (NewBeeMallShoppingCartItemVO myShoppingCartItem : myShoppingCartItems) {
                    NewBeeMallGoods good = newBeeMallGoodsService.getNewBeeMallGoodsById(myShoppingCartItem.getGoodsId());
                    if (good.getGoodsSellStatus() == 0 && good.getStockNum() >= myShoppingCartItem.getGoodsCount()) {
                        good.setStockNum(good.getStockNum() - myShoppingCartItem.getGoodsCount());
                        updateGoods.add(good);
                    }
                }
                if (updateGoods.isEmpty() || newBeeMallGoodsService.batchUpdateGoods(updateGoods)) {
                    NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_COUNT_ERROR.getResult());
                }
                //生成订单号
                String orderNo = NumberUtil.genOrderNo();
                int priceTotal = 0;
                //保存订单
                NewBeeMallOrder newBeeMallOrder = new NewBeeMallOrder();
                newBeeMallOrder.setOrderNo(orderNo);
                newBeeMallOrder.setUserId(loginMallUser.getUserId());
                //总价
                for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {
                    priceTotal += newBeeMallShoppingCartItemVO.getGoodsCount() * newBeeMallShoppingCartItemVO.getSellingPrice();
                }
                if (priceTotal < 1) {
                    NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
                }
                newBeeMallOrder.setTotalPrice(priceTotal);
                String extraInfo = "";
                newBeeMallOrder.setExtraInfo(extraInfo);
                //生成订单项并保存订单项纪录
                if (newBeeMallOrderMapper.insert(newBeeMallOrder) > 0) {
                    //生成订单收货地址快照，并保存至数据库
                    NewBeeMallOrderAddress newBeeMallOrderAddress = new NewBeeMallOrderAddress();
                    BeanUtil.copyProperties(address, newBeeMallOrderAddress);
                    newBeeMallOrderAddress.setOrderId(newBeeMallOrder.getOrderId());
                    //生成所有的订单项快照，并保存至数据库
                    List<NewBeeMallOrderItem> newBeeMallOrderItems = new ArrayList<>();
                    for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {
                        NewBeeMallOrderItem newBeeMallOrderItem = new NewBeeMallOrderItem();
                        //使用BeanUtil工具类将newBeeMallShoppingCartItemVO中的属性复制到newBeeMallOrderItem对象中
                        BeanUtil.copyProperties(newBeeMallShoppingCartItemVO, newBeeMallOrderItem);
                        //NewBeeMallOrderMapper文件insert()方法中使用了useGeneratedKeys因此orderId可以获取到
                        newBeeMallOrderItem.setOrderId(newBeeMallOrder.getOrderId());
                        newBeeMallOrderItems.add(newBeeMallOrderItem);
                    }
                    //保存至数据库
                    if (!newBeeMallOrderItemMapper.insert(newBeeMallOrderItems).isEmpty() && newBeeMallOrderAddressMapper.insert(newBeeMallOrderAddress) > 0) {
                        //所有操作成功后，将订单号返回，以供Controller方法跳转到订单详情
                        return orderNo;
                    }
                    NewBeeMallException.fail(ServiceResultEnum.ORDER_PRICE_ERROR.getResult());
                }
                NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
            }
            NewBeeMallException.fail(ServiceResultEnum.DB_ERROR.getResult());
        }
        NewBeeMallException.fail(ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult());
        return ServiceResultEnum.SHOPPING_ITEM_ERROR.getResult();
    }

    @Override
    public PageResult<NewBeeMallOrder> getNewBeeMallOrdersPage(PageQuery pageQuery) {
        String orderNo = (String) pageQuery.get("orderNo");
        String userId = (String) pageQuery.get("userId");
        String payType = (String) pageQuery.get("payType");
        String orderStatus = (String) pageQuery.get("orderStatus");
        String isDeleted = (String) pageQuery.get("isDeleted");
        String startTime = (String) pageQuery.get("startTime");
        String endTime = (String) pageQuery.get("endTime");

        Page<NewBeeMallOrder> page = new Page<>(pageQuery.getPageIndex(), pageQuery.getPageSize());
        LambdaQueryWrapper<NewBeeMallOrder> queryWrapper = Wrappers.lambdaQuery();
        if (orderNo != null) {
            queryWrapper.eq(NewBeeMallOrder::getOrderNo, orderNo);
        }
        if (userId != null) {
            queryWrapper.eq(NewBeeMallOrder::getUserId, userId);
        }
        if (payType != null) {
            queryWrapper.eq(NewBeeMallOrder::getPayType, payType);
        }
        if (orderStatus != null) {
            queryWrapper.eq(NewBeeMallOrder::getOrderStatus, orderStatus);
        }
        if (isDeleted != null) {
            queryWrapper.eq(NewBeeMallOrder::getIsDeleted, isDeleted);
        }
        if (startTime != null) {
            queryWrapper.ge(NewBeeMallOrder::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(NewBeeMallOrder::getCreateTime, endTime);
        }
        queryWrapper.orderByDesc(NewBeeMallOrder::getCreateTime);
        IPage<NewBeeMallOrder> pageData = newBeeMallOrderMapper.selectPage(page, queryWrapper);
        return new PageResult(pageData.getRecords(), (int) pageData.getTotal(), (int) pageData.getSize(), (int) pageData.getCurrent());
    }

    @Override
    public String updateOrderInfo(NewBeeMallOrder newBeeMallOrder) {
        NewBeeMallOrder temp = findOrderByOrderId(newBeeMallOrder.getOrderId());
        //不为空且orderStatus>=0且状态为出库之前可以修改部分信息
        if (temp != null && temp.getOrderStatus() >= 0 && temp.getOrderStatus() < 3) {
            LambdaUpdateWrapper<NewBeeMallOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(NewBeeMallOrder::getTotalPrice, newBeeMallOrder.getTotalPrice())
                    .set(NewBeeMallOrder::getUpdateTime, new Date())
                    .eq(NewBeeMallOrder::getOrderId, newBeeMallOrder.getOrderId());
            if (newBeeMallOrderMapper.update(null, updateWrapper) > 0) {
                return ServiceResultEnum.SUCCESS.getResult();
            }
            return ServiceResultEnum.DB_ERROR.getResult();
        }
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    public String checkDone(Long[] ids) {
        //查询所有的订单 判断状态 修改状态和更新时间
        List<NewBeeMallOrder> orders = findOrderByOrderIds(Arrays.asList(ids));
        String errorOrderNos = "";
        if (!CollectionUtils.isEmpty(orders)) {
            for (NewBeeMallOrder newBeeMallOrder : orders) {
                if (newBeeMallOrder.getIsDeleted() == 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                    continue;
                }
                if (newBeeMallOrder.getOrderStatus() != 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                }
            }
            if (!StringUtils.hasText(errorOrderNos)) {
                //订单状态正常 可以执行配货完成操作 修改订单状态和更新时间
                if (updateOrderStatusByOrderIds(Arrays.asList(ids), (byte) NewBeeMallOrderStatusEnum.ORDER_PACKAGED.getOrderStatus()) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                //订单此时不可执行出库操作
                if (errorOrderNos.length() > 0 && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单的状态不是支付成功无法执行出库操作";
                } else {
                    return "你选择了太多状态不是支付成功的订单，无法执行配货完成操作";
                }
            }
        }
        //未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    public String checkOut(Long[] ids) {
        //查询所有的订单 判断状态 修改状态和更新时间
        List<NewBeeMallOrder> orders = findOrderByOrderIds(Arrays.asList(ids));
        String errorOrderNos = "";
        if (!CollectionUtils.isEmpty(orders)) {
            for (NewBeeMallOrder newBeeMallOrder : orders) {
                if (newBeeMallOrder.getIsDeleted() == 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                    continue;
                }
                if (newBeeMallOrder.getOrderStatus() != 1 && newBeeMallOrder.getOrderStatus() != 2) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                }
            }
            if (!StringUtils.hasText(errorOrderNos)) {
                //订单状态正常 可以执行出库操作 修改订单状态和更新时间
                if (updateOrderStatusByOrderIds(Arrays.asList(ids), (byte) NewBeeMallOrderStatusEnum.ORDER_EXPRESS.getOrderStatus()) > 0) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                //订单此时不可执行出库操作
                if (!errorOrderNos.isEmpty() && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单的状态不是支付成功或配货完成无法执行出库操作";
                } else {
                    return "你选择了太多状态不是支付成功或配货完成的订单，无法执行出库操作";
                }
            }
        }
        //未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    public String closeOrder(Long[] ids) {
        //查询所有的订单 判断状态 修改状态和更新时间
        List<NewBeeMallOrder> orders = findOrderByOrderIds(Arrays.asList(ids));
        String errorOrderNos = "";
        if (!CollectionUtils.isEmpty(orders)) {
            for (NewBeeMallOrder newBeeMallOrder : orders) {
                // isDeleted=1 一定为已关闭订单
                if (newBeeMallOrder.getIsDeleted() == 1) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                    continue;
                }
                //已关闭或者已完成无法关闭订单
                if (newBeeMallOrder.getOrderStatus() == 4 || newBeeMallOrder.getOrderStatus() < 0) {
                    errorOrderNos += newBeeMallOrder.getOrderNo() + " ";
                }
            }
            if (!StringUtils.hasText(errorOrderNos)) {
                //订单状态正常 可以执行关闭操作 修改订单状态和更新时间&&恢复库存
                if (updateOrderStatusByOrderIds(Arrays.asList(ids), (byte) NewBeeMallOrderStatusEnum.ORDER_CLOSED_BY_JUDGE.getOrderStatus()) > 0 && recoverStockNum(Arrays.asList(ids))) {
                    return ServiceResultEnum.SUCCESS.getResult();
                } else {
                    return ServiceResultEnum.DB_ERROR.getResult();
                }
            } else {
                //订单此时不可执行关闭操作
                if (!errorOrderNos.isEmpty() && errorOrderNos.length() < 100) {
                    return errorOrderNos + "订单不能执行关闭操作";
                } else {
                    return "你选择的订单不能执行关闭操作";
                }
            }
        }
        //未查询到数据 返回错误提示
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    public List<NewBeeMallOrderItemVO> getOrderItems(Long orderId) {
        NewBeeMallOrder newBeeMallOrder = findOrderByOrderId(orderId);
        if (newBeeMallOrder != null) {
            List<NewBeeMallOrderItem> orderItems = newBeeMallOrderItemService.findByOrderItemId(newBeeMallOrder.getOrderId());
            //获取订单项数据
            if (!CollectionUtils.isEmpty(orderItems)) {
                return BeanUtil.copyList(orderItems, NewBeeMallOrderItemVO.class);
            }
        }
        return null;
    }

    public Boolean recoverStockNum(List<Long> orderIds) {
        //查询对应的订单项
        LambdaQueryWrapper<NewBeeMallOrderItem> orderQueryWrapper = Wrappers.lambdaQuery();
        orderQueryWrapper.in(NewBeeMallOrderItem::getOrderId, orderIds);
        List<NewBeeMallOrderItem> newBeeMallOrderItems = newBeeMallOrderItemMapper.selectList(orderQueryWrapper);
        List<NewBeeMallGoods> updateGoods = new ArrayList<>();
        for (NewBeeMallOrderItem newBeeMallOrderItem : newBeeMallOrderItems) {
            NewBeeMallGoods good = newBeeMallGoodsService.getNewBeeMallGoodsById(newBeeMallOrderItem.getGoodsId());
            if (good.getGoodsSellStatus() == 0) {
                good.setStockNum(good.getStockNum() + newBeeMallOrderItem.getGoodsCount());
                updateGoods.add(good);
            }
        }
        if (updateGoods.isEmpty() || newBeeMallGoodsService.batchUpdateGoods(updateGoods)) {
            NewBeeMallException.fail(ServiceResultEnum.CLOSE_ORDER_ERROR.getResult());
            return false;
        } else {
            return true;
        }
    }

    private NewBeeMallOrder findOrderByOrderId(Long orderId) {
        LambdaQueryWrapper<NewBeeMallOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(NewBeeMallOrder::getOrderId, orderId);
        return newBeeMallOrderMapper.selectOne(orderQueryWrapper);
    }

    private List<NewBeeMallOrder> findOrderByOrderIds(List<Long> orderIds) {
        LambdaQueryWrapper<NewBeeMallOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.in(NewBeeMallOrder::getOrderId, orderIds);
        return newBeeMallOrderMapper.selectList(orderQueryWrapper);
    }

    private int updateOrderStatusByOrderIds(List<Long> orderIds, byte orderStatus) {
        LambdaUpdateWrapper<NewBeeMallOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .set(NewBeeMallOrder::getOrderStatus, orderStatus)
                .set(NewBeeMallOrder::getUpdateTime, new Date())
                .in(NewBeeMallOrder::getOrderId, orderIds);
        return newBeeMallOrderMapper.update(null, updateWrapper);
    }

    private NewBeeMallOrder findOrderByOrderNo(String orderNo) {
        LambdaQueryWrapper<NewBeeMallOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper
                .eq(NewBeeMallOrder::getOrderNo, orderNo)
                .eq(NewBeeMallOrder::getIsDeleted, 0);
        return newBeeMallOrderMapper.selectOne(orderQueryWrapper);
    }
}
